package service

import (
	"encoding/json"
	"gitee.com/jikey/elk-blog/app/model"
	db "gitee.com/jikey/elk-blog/app/model"
)

type system struct {
}

var System *system

// GetSystemList 获取 Article 分类列表
func (c *system) GetSystemList(systemId int) (systems []*model.System) {
	db.Mysql.Select("*").Where("id = ? ", systemId).Order("id ASC").Find(&systems)

	return
}

// GetSystem 获取 System
func (c *system) GetSystem(systemId int) (system model.System) {
	db.Mysql.Where("id = ? ", systemId).First(&system)

	return
}

// Create 新增
func (c *system) Create(model *model.System) (err error) {
	err = db.Mysql.Create(model).Error

	return err
}

// Update 修改
func (c *system) Update(systemId string, model *model.System) (err error) {
	data, _ := json.Marshal(&model)
	m := make(map[string]interface{})
	err = json.Unmarshal(data, &m)

	if err != nil {
		return err
	}

	// 使用map更新含0值字段，使用struct无法更新
	err = db.Mysql.Model(&model).Where("Id = ? ", systemId).Updates(m).Error

	return err
}

// Delete 删除
func (c *system) Delete(id int) (rowsAffected int64) {
	result := db.Mysql.Where("Id = ?", id).Delete(&system{})

	return result.RowsAffected
}
